from django.shortcuts import render

# Create your views here.
from django.core.cache import cache
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
# from message.models import Message

# Create your views here.
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.cache import cache_page

from tools.login_dec import login_check, get_user_by_request
import json
import html
from .models import Topic
from user.models import UserProfile
from tools.cache_dec import topic_cache


class TopicView(View):
    def clean_topic_cache(self, request):
        # 当发表文章\删除文章时,需要清除缓存
        # 我们一共6种缓存[10分钟],16:35回来
        # 删除前,缓存键打印以下,确保键是正确的
        # cache.delete_many(键列表)
        keys_b = ['topic_cache_self_', 'topic_cache_']
        keys_m = request.path_info
        keys_p = ['', '?category=tec', '?category=no-tec']
        all_keys = []
        for key_b in keys_b:
            for key_p in keys_p:
                key = key_b + keys_m + key_p
                all_keys.append(key)
        print('*********all keys*******************')
        print(all_keys)
        cache.delete_many(all_keys)

    # 博客详情的返回值
    def make_topic_res(self, author, author_topic, is_self):
        print('******make_topic_res**********')
        result = {'code': 200, 'data': {}}
        # 第一部分
        result['data']['nickname'] = author.nickname
        result['data']['title'] = author_topic.title
        result['data']['category'] = author_topic.category
        result['data']['content'] = author_topic.content
        result['data']['introduce'] = author_topic.introduce
        result['data']['author'] = author.nickname
        result['data']['created_time'] = \
            author_topic.created_time.strftime('%Y-%m-%d %H:%M:%S')
        # 第二部分
        if is_self:
            # 博主自己访问,不需要权限过滤
            next_topic = Topic.objects.filter(id__gt=author_topic.id,
                                              user_profile_id=author.username).first()
            last_topic = Topic.objects.filter(id__lt=author_topic.id,
                                              user_profile_id=author.username).last()
        else:
            # 非博主访问,需要权限过滤
            next_topic = Topic.objects.filter(id__gt=author_topic.id,
                                              user_profile_id=author.username,
                                              limit='public').first()
            last_topic = Topic.objects.filter(id__lt=author_topic.id,
                                              user_profile_id=author.username,
                                              limit='public').last()
        if next_topic:
            next_id = next_topic.id
            next_title = next_topic.title
        else:
            next_id = None
            next_title = None

        if last_topic:
            last_id = last_topic.id
            last_title = last_topic.title
        else:
            last_id = None
            last_title = None

        result['data']['last_id'] = last_id
        result['data']['last_title'] = last_title
        result['data']['next_id'] = next_id
        result['data']['next_title'] = next_title



        # 第三部分
        all_msgs=Message.objects.filter(topic=author_topic)
        msg_list=[]
        r_dict=[]
        msg_count=0
        for msg in all_msgs:
            if msg.parent_message:
                # 回复[组员]
                r_dict.setdefault(msg.parent_message,[])
                r_dict[msg.parent_message].append(
                    {
                        'publish': msg.user_profile.nickname,
                        'publisher_avatar': str(msg.user_profile.avatar),
                        'create_time': msg.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    }
                )

            else:
                # 评论[组长]
                msg_count+=1
                msg_list.append(
                    {
                        'id':msg.id,
                        'content':msg.content,
                        'publish':msg.user_profile.nickname,
                        'publisher_avatar':str(msg.user_profile.avatar),
                        'create_time':msg.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'reply':[],
                    }
                )


        for m in msg_list:
            if m['id'] in r_dict:
                m['reply']=r_dict[m['id']]
        print(msg_list)
        result['data']['messages'] = msg_list
        result['data']['messages_count'] = msg_count
        # 返回
        return result

        # 博客列表的返回值

    def make_topics_res(self, author, author_topics):
        # 1 保存文章列表的变量
        topics_res = []
        for topic in author_topics:
            d = {}
            d['id'] = topic.id
            d['title'] = topic.title
            d['category'] = topic.category
            d['introduce'] = topic.introduce
            d['created_time'] = \
                topic.created_time.strftime('%Y-%m-%d %H:%M:%S')
            d['author'] = author.nickname
            topics_res.append(d)
        res = {'code': 200, 'data': {}}
        res['data']['nickname'] = author.nickname
        res['data']['topics'] = topics_res
        return res

    @method_decorator(login_check)
    def post(self, request, author_id):
        # add your code here
        # 1 获取前端提交的数据json_str
        json_str = request.body
        # 2 将json_str反序列化为python对象
        py_obj = json.loads(json_str)
        title = py_obj['title']
        category = py_obj['category']
        content_text = py_obj['content_text']
        content = py_obj['content']
        limit = py_obj['limit']
        # print(title, category, limit, content, content_text)
        # 3 数据校验
        if limit not in ['public', 'private']:
            result = {'code': 30100, 'error': '权限错误'}
            return JsonResponse(result)
        if category not in ['tec', 'no-tec']:
            result = {'code': 30101, 'error': '分类错误'}
            return JsonResponse(result)
        if not content_text:
            result = {'code': 30102, 'error': '内容不能为空'}
            return JsonResponse(result)
        introduce = content_text[:20]
        # 4 转义,抵御XSS攻击.对标题做转义
        # 内容使用了wangEditor,自动做转义的
        title = html.escape(title)
        # 5 文章作者,从request.myuser
        user = request.myuser
        # 6 添加到数据库
        Topic.objects.create(title=title,
                             category=category,
                             limit=limit,
                             content=content,
                             introduce=introduce,
                             user_profile=user)
        # 7,发表博客,博客列表就会发生变化,所以需要清除缓存
        # add your code here
        self.clean_topic_cache(request)
        return JsonResponse({'code': 200})

    @method_decorator(topic_cache(600))
    def get(self, request, author_id):
        print('********** get view in *********')
        # 1. 根据author_id获取博客的博主
        try:
            author = UserProfile.objects.get(username=author_id)
        except:
            result = {'code': 30103, 'error': '用户名称错误'}
            return JsonResponse(result)
        # 2. 获取访问者(可以为空,表示游客)
        visitor = get_user_by_request(request)
        print(visitor, author_id)

        # 另外定义一个变量,表示是否是博主访问自己
        # 默认不是博主访问自己
        is_self = False
        # 获取文章ID
        t_id = request.GET.get('t_id')
        if t_id:
            print('******t_id不为空***********')
            # 获取详情页
            # 博主访问自己,不用做权限过滤
            if visitor == author_id:
                is_self = True
                try:
                    author_topic = Topic.objects.get(id=t_id,
                                                     user_profile_id=author_id)
                except:
                    result = {'code': 30104, 'error': '文章标题错误!'}
                    return JsonResponse(result)


            # 非博主访问,只能public,增加权限
            else:
                try:
                    author_topic = Topic.objects.get(id=t_id,
                                                     user_profile_id=author_id,
                                                     limit='public')
                except:
                    result = {'code': 30104, 'error': '文章标题错误!'}
                    return JsonResponse(result)

            # 将数据封装成json格式返回
            res = self.make_topic_res(author, author_topic, is_self)
            return JsonResponse(res)


        else:
            ## 获取列表页
            # 分类问题
            category = request.GET.get('category')
            # 定义变量,默认是没有分类
            filter_category = False
            if category in ['tec', 'no-tec']:
                filter_category = True
            # 3. 比较两者,就能判断是否是博主访问自己
            if visitor == author_id:
                # 不做权限过滤
                if filter_category:
                    # 做分类过滤
                    author_topics = Topic.objects.filter(user_profile_id=author_id,
                                                         category=category)
                else:
                    # 不做分类过滤
                    author_topics = Topic.objects.filter(user_profile_id=author_id)

            else:
                # 做权限过滤
                if filter_category:
                    # 做分类过滤
                    author_topics = Topic.objects.filter(user_profile_id=author_id,
                                                         category=category,
                                                         limit='public')
                else:
                    # 不做分类过滤
                    author_topics = Topic.objects.filter(user_profile_id=author_id,
                                                         limit='public')
            # 将查询结果封装成前端需要的JSON格式
            res = self.make_topics_res(author,
                                       author_topics)
            return JsonResponse(res)
